<template>
  <div class="stats-page">
    <!-- 页面标题 -->
    <div class="page-header mb-6">
      <div class="flex justify-between items-center">
        <div>
          <h1 class="text-2xl font-bold text-slate-800 ">数据统计</h1>
        </div>
        <div class="flex space-x-3">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="dateShortcuts"
            @change="handleDateChange"
          />
          <el-button type="primary" @click="refreshData">
            <el-icon class="mr-1"><i class="el-icon-refresh"></i></el-icon>刷新数据
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 数据概览 -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
      <el-card shadow="never" class="stat-card">
        <div class="flex items-center">
          <div class="stat-icon bg-blue-100 text-blue-500  ">
            <i class="el-icon-view"></i>
          </div>
          <div class="ml-4">
            <div class="text-gray-500 text-sm">总访问量</div>
            <div class="text-2xl font-bold mt-1">{{ formatNumber(overviewData.totalVisits) }}</div>
            <div class="text-xs mt-1">
              <span :class="overviewData.visitsChange >= 0 ? 'text-green-500' : 'text-red-500'">
                <i :class="overviewData.visitsChange >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                {{ Math.abs(overviewData.visitsChange) }}%
              </span>
              <span class="text-gray-400 ml-1">较上期</span>
            </div>
          </div>
        </div>
      </el-card>
      
      <el-card shadow="never" class="stat-card">
        <div class="flex items-center">
          <div class="stat-icon bg-green-100 text-green-500  ">
            <i class="el-icon-user"></i>
          </div>
          <div class="ml-4">
            <div class="text-gray-500 text-sm">独立访客</div>
            <div class="text-2xl font-bold mt-1">{{ formatNumber(overviewData.uniqueVisitors) }}</div>
            <div class="text-xs mt-1">
              <span :class="overviewData.visitorsChange >= 0 ? 'text-green-500' : 'text-red-500'">
                <i :class="overviewData.visitorsChange >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                {{ Math.abs(overviewData.visitorsChange) }}%
              </span>
              <span class="text-gray-400 ml-1">较上期</span>
            </div>
          </div>
        </div>
      </el-card>
      
      <el-card shadow="never" class="stat-card">
        <div class="flex items-center">
          <div class="stat-icon bg-orange-100 text-orange-500  ">
            <i class="el-icon-reading"></i>
          </div>
          <div class="ml-4">
            <div class="text-gray-500 text-sm">新闻阅读量</div>
            <div class="text-2xl font-bold mt-1">{{ formatNumber(overviewData.newsReads) }}</div>
            <div class="text-xs mt-1">
              <span :class="overviewData.readsChange >= 0 ? 'text-green-500' : 'text-red-500'">
                <i :class="overviewData.readsChange >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                {{ Math.abs(overviewData.readsChange) }}%
              </span>
              <span class="text-gray-400 ml-1">较上期</span>
            </div>
          </div>
        </div>
      </el-card>
      
      <el-card shadow="never" class="stat-card">
        <div class="flex items-center">
          <div class="stat-icon bg-red-100 text-red-500  ">
            <i class="el-icon-document"></i>
          </div>
          <div class="ml-4">
            <div class="text-gray-500 text-sm">新闻总数</div>
            <div class="text-2xl font-bold mt-1">{{ formatNumber(overviewData.totalNews) }}</div>
            <div class="text-xs mt-1">
              <span :class="overviewData.newsChange >= 0 ? 'text-green-500' : 'text-red-500'">
                <i :class="overviewData.newsChange >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                {{ Math.abs(overviewData.newsChange) }}%
              </span>
              <span class="text-gray-400 ml-1">较上期</span>
            </div>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 访问趋势图 -->
    <el-card shadow="never" class="mb-6">
      <template #header>
        <div class="flex justify-between items-center">
          <div class="text-lg font-medium">访问趋势</div>
          <div>
            <el-radio-group v-model="trendTimeUnit" size="small" @change="handleTrendUnitChange">
              <el-radio-button label="day">日</el-radio-button>
              <el-radio-button label="week">周</el-radio-button>
              <el-radio-button label="month">月</el-radio-button>
            </el-radio-group>
          </div>
        </div>
      </template>
      <div class="h-80" ref="visitTrendChart"></div>
    </el-card>
    
    <!-- 内容分析和用户分析 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
      <!-- 内容分析 -->
      <el-card shadow="never">
        <template #header>
          <div class="flex justify-between items-center">
            <div class="text-lg font-medium">内容分析</div>
            <el-tabs v-model="contentAnalysisTab" class="content-tabs" @tab-change="handleContentTabChange">
              <el-tab-pane label="分类分布" name="category"></el-tab-pane>
              <el-tab-pane label="区域分布" name="region"></el-tab-pane>
              <el-tab-pane label="信源分布" name="source"></el-tab-pane>
            </el-tabs>
          </div>
        </template>
        <div class="h-80" ref="contentAnalysisChart"></div>
      </el-card>
      
      <!-- 用户分析 -->
      <el-card shadow="never">
        <template #header>
          <div class="flex justify-between items-center">
            <div class="text-lg font-medium">用户分析</div>
            <el-tabs v-model="userAnalysisTab" class="user-tabs" @tab-change="handleUserTabChange">
              <el-tab-pane label="访问设备" name="device"></el-tab-pane>
              <el-tab-pane label="访问来源" name="source"></el-tab-pane>
              <el-tab-pane label="地域分布" name="region"></el-tab-pane>
            </el-tabs>
          </div>
        </template>
        <div class="h-80" ref="userAnalysisChart"></div>
      </el-card>
    </div>
    
    <!-- 热门内容和访问页面 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
      <!-- 热门内容 -->
      <el-card shadow="never">
        <template #header>
          <div class="flex justify-between items-center">
            <div class="text-lg font-medium">热门内容</div>
            <el-select v-model="popularContentType" size="small" @change="handlePopularContentTypeChange">
              <el-option label="阅读量" value="reads"></el-option>
              <el-option label="分享量" value="shares"></el-option>
              <el-option label="停留时间" value="duration"></el-option>
            </el-select>
          </div>
        </template>
        <el-table :data="popularContent" style="width: 100%" :max-height="400">
          <el-table-column prop="rank" label="排名" width="70">
            <template #default="scope">
              <div class="flex items-center justify-center">
                <div :class="getRankClass(scope.row.rank)">
                  {{ scope.row.rank }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="title" label="标题" min-width="200">
            <template #default="scope">
              <div class="truncate">
                <el-tooltip :content="scope.row.title" placement="top" :show-after="1000">
                  <span class="cursor-pointer hover:text-primary-500" @click="viewNews(scope.row.id)">
                    {{ scope.row.title }}
                  </span>
                </el-tooltip>
              </div>
              <div class="text-xs text-gray-500 mt-1">
                {{ scope.row.category }} · {{ scope.row.source }} · {{ scope.row.publish_time }}
              </div>
            </template>
          </el-table-column>
          <el-table-column :prop="popularContentType" :label="getPopularContentTypeLabel()" width="120" align="right">
            <template #default="scope">
              <div class="font-medium">
                {{ formatPopularContentValue(scope.row[popularContentType]) }}
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      
      <!-- 访问页面 -->
      <el-card shadow="never">
        <template #header>
          <div class="flex justify-between items-center">
            <div class="text-lg font-medium">访问页面</div>
            <el-select v-model="pageMetricType" size="small" @change="handlePageMetricTypeChange">
              <el-option label="访问量" value="pv"></el-option>
              <el-option label="访客数" value="uv"></el-option>
              <el-option label="跳出率" value="bounce_rate"></el-option>
            </el-select>
          </div>
        </template>
        <el-table :data="visitedPages" style="width: 100%" :max-height="400">
          <el-table-column prop="rank" label="排名" width="70">
            <template #default="scope">
              <div class="flex items-center justify-center">
                <div :class="getRankClass(scope.row.rank)">
                  {{ scope.row.rank }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="page" label="页面" min-width="200">
            <template #default="scope">
              <div class="truncate">
                <el-tooltip :content="scope.row.page" placement="top" :show-after="1000">
                  <span class="cursor-pointer hover:text-primary-500">
                    {{ scope.row.page }}
                  </span>
                </el-tooltip>
              </div>
              <div class="text-xs text-gray-500 mt-1">
                {{ scope.row.path }}
              </div>
            </template>
          </el-table-column>
          <el-table-column :prop="pageMetricType" :label="getPageMetricTypeLabel()" width="120" align="right">
            <template #default="scope">
              <div class="font-medium">
                {{ formatPageMetricValue(scope.row[pageMetricType]) }}
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import * as echarts from 'echarts/core'
import { BarChart, LineChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent
} from 'echarts/components'
import { LabelLayout, UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'

// 注册 ECharts 组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  BarChart,
  LineChart,
  PieChart,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer
])

// 设置使用管理布局
definePageMeta({
  layout: 'admin'
})

// 图表实例
let visitTrendChartInstance = null
let contentAnalysisChartInstance = null
let userAnalysisChartInstance = null

// 图表DOM引用
const visitTrendChart = ref(null)
const contentAnalysisChart = ref(null)
const userAnalysisChart = ref(null)

// 日期范围选择
const dateRange = ref([new Date(Date.now() - 30 * 24 * 60 * 60 * 1000), new Date()])
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]

// 趋势图时间单位
const trendTimeUnit = ref('day')

// 内容分析和用户分析标签页
const contentAnalysisTab = ref('category')
const userAnalysisTab = ref('device')

// 热门内容和访问页面筛选
const popularContentType = ref('reads')
const pageMetricType = ref('pv')

// 数据概览
const overviewData = reactive({
  totalVisits: 125689,
  visitsChange: 12.5,
  uniqueVisitors: 45782,
  visitorsChange: 8.3,
  newsReads: 98456,
  readsChange: 15.2,
  totalNews: 3254,
  newsChange: 5.7
})

// 热门内容数据
const popularContent = ref([
  { rank: 1, id: 101, title: '国务院关于加强经济发展的重要指示', category: '国内', source: '新华网', publish_time: '2023-06-15', reads: 12500, shares: 3450, duration: 245 },
  { rank: 2, id: 102, title: '美联储宣布加息25个基点，为今年第三次加息', category: '财经', source: '财经日报', publish_time: '2023-06-14', reads: 10200, shares: 2800, duration: 210 },
  { rank: 3, id: 103, title: '世界杯预选赛：中国队2:0战胜泰国队', category: '体育', source: '体育周报', publish_time: '2023-06-13', reads: 9800, shares: 4200, duration: 180 },
  { rank: 4, id: 104, title: '新一代人工智能技术发展报告发布', category: '科技', source: '科技日报', publish_time: '2023-06-12', reads: 8500, shares: 2100, duration: 195 },
  { rank: 5, id: 105, title: '电影《流浪地球3》定档明年春节', category: '娱乐', source: '娱乐周刊', publish_time: '2023-06-11', reads: 7900, shares: 3600, duration: 165 },
  { rank: 6, id: 106, title: '全国高考成绩将于本月25日起陆续公布', category: '教育', source: '教育在线', publish_time: '2023-06-10', reads: 7500, shares: 1800, duration: 155 },
  { rank: 7, id: 107, title: '夏季养生指南：如何科学防暑降温', category: '健康', source: '健康时报', publish_time: '2023-06-09', reads: 6800, shares: 2500, duration: 140 },
  { rank: 8, id: 108, title: '国内多地出台新政策促进房地产市场健康发展', category: '国内', source: '经济观察报', publish_time: '2023-06-08', reads: 6200, shares: 1500, duration: 185 },
  { rank: 9, id: 109, title: '欧盟通过新法案规范人工智能应用', category: '国际', source: '国际先驱导报', publish_time: '2023-06-07', reads: 5800, shares: 1200, duration: 175 },
  { rank: 10, id: 110, title: '专家解读：如何看待当前经济形势', category: '财经', source: '财经网', publish_time: '2023-06-06', reads: 5500, shares: 980, duration: 160 }
])

// 访问页面数据
const visitedPages = ref([
  { rank: 1, page: '首页', path: '/', pv: 45600, uv: 25400, bounce_rate: 35.2 },
  { rank: 2, page: '国内新闻', path: '/category/domestic', pv: 32500, uv: 18700, bounce_rate: 42.5 },
  { rank: 3, page: '国际新闻', path: '/category/international', pv: 28900, uv: 16500, bounce_rate: 38.7 },
  { rank: 4, page: '财经新闻', path: '/category/finance', pv: 25400, uv: 14200, bounce_rate: 45.3 },
  { rank: 5, page: '科技新闻', path: '/category/tech', pv: 22800, uv: 13600, bounce_rate: 40.1 },
  { rank: 6, page: '体育新闻', path: '/category/sports', pv: 21500, uv: 12800, bounce_rate: 36.8 },
  { rank: 7, page: '娱乐新闻', path: '/category/entertainment', pv: 19700, uv: 11500, bounce_rate: 48.2 },
  { rank: 8, page: '教育新闻', path: '/category/education', pv: 15600, uv: 9800, bounce_rate: 52.4 },
  { rank: 9, page: '健康新闻', path: '/category/health', pv: 14200, uv: 8900, bounce_rate: 47.6 },
  { rank: 10, page: '搜索页面', path: '/search', pv: 12800, uv: 10200, bounce_rate: 28.5 }
])

// 格式化数字
const formatNumber = (num) => {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + '万'
  }
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

// 获取排名样式
const getRankClass = (rank) => {
  const baseClass = 'w-6 h-6 rounded-full flex items-center justify-center text-xs font-medium'
  if (rank === 1) {
    return `${baseClass} bg-red-100 text-red-500  `
  } else if (rank === 2) {
    return `${baseClass} bg-orange-100 text-orange-500  `
  } else if (rank === 3) {
    return `${baseClass} bg-yellow-100 text-yellow-500  `
  } else {
    return `${baseClass} bg-gray-100 text-gray-500  `
  }
}

// 获取热门内容类型标签
const getPopularContentTypeLabel = () => {
  switch (popularContentType.value) {
    case 'reads':
      return '阅读量'
    case 'shares':
      return '分享量'
    case 'duration':
      return '停留时间'
    default:
      return '阅读量'
  }
}

// 格式化热门内容值
const formatPopularContentValue = (value) => {
  if (popularContentType.value === 'duration') {
    // 将秒转换为分:秒格式
    const minutes = Math.floor(value / 60)
    const seconds = value % 60
    return `${minutes}:${seconds.toString().padStart(2, '0')}`
  } else {
    return formatNumber(value)
  }
}

// 获取页面指标类型标签
const getPageMetricTypeLabel = () => {
  switch (pageMetricType.value) {
    case 'pv':
      return '访问量'
    case 'uv':
      return '访客数'
    case 'bounce_rate':
      return '跳出率'
    default:
      return '访问量'
  }
}

// 格式化页面指标值
const formatPageMetricValue = (value) => {
  if (pageMetricType.value === 'bounce_rate') {
    return `${value}%`
  } else {
    return formatNumber(value)
  }
}

// 查看新闻详情
const viewNews = (id) => {
  // 跳转到新闻详情页
  navigateTo(`/admin/news/detail/${id}`)
}

// 日期变化处理
const handleDateChange = () => {
  // 重新加载数据
  refreshData()
}

// 趋势图时间单位变化处理
const handleTrendUnitChange = () => {
  // 重新渲染趋势图
  renderVisitTrendChart()
}

// 内容分析标签页变化处理
const handleContentTabChange = () => {
  // 重新渲染内容分析图
  renderContentAnalysisChart()
}

// 用户分析标签页变化处理
const handleUserTabChange = () => {
  // 重新渲染用户分析图
  renderUserAnalysisChart()
}

// 热门内容类型变化处理
const handlePopularContentTypeChange = () => {
  // 重新排序热门内容
  popularContent.value.sort((a, b) => b[popularContentType.value] - a[popularContentType.value])
  // 重新设置排名
  popularContent.value.forEach((item, index) => {
    item.rank = index + 1
  })
}

// 页面指标类型变化处理
const handlePageMetricTypeChange = () => {
  // 重新排序访问页面
  if (pageMetricType.value === 'bounce_rate') {
    // 跳出率从低到高排序
    visitedPages.value.sort((a, b) => a[pageMetricType.value] - b[pageMetricType.value])
  } else {
    // 其他指标从高到低排序
    visitedPages.value.sort((a, b) => b[pageMetricType.value] - a[pageMetricType.value])
  }
  // 重新设置排名
  visitedPages.value.forEach((item, index) => {
    item.rank = index + 1
  })
}

// 刷新数据
const refreshData = () => {
  // 这里应该是实际的数据加载逻辑
  // 模拟数据加载
  ElMessage({
    type: 'success',
    message: '数据已刷新',
  })
  
  // 重新渲染所有图表
  nextTick(() => {
    renderVisitTrendChart()
    renderContentAnalysisChart()
    renderUserAnalysisChart()
  })
}

// 渲染访问趋势图
const renderVisitTrendChart = () => {
  if (!visitTrendChart.value) return
  
  // 销毁旧实例
  if (visitTrendChartInstance) {
    visitTrendChartInstance.dispose()
  }
  
  // 创建新实例
  visitTrendChartInstance = echarts.init(visitTrendChart.value, null, {
    renderer: 'canvas'
  })
  
  // 模拟数据
  let xAxisData = []
  let visitData = []
  let visitorData = []
  
  // 根据时间单位生成数据
  if (trendTimeUnit.value === 'day') {
    // 日数据，最近30天
    for (let i = 29; i >= 0; i--) {
      const date = new Date()
      date.setDate(date.getDate() - i)
      xAxisData.push(`${date.getMonth() + 1}/${date.getDate()}`)
      visitData.push(Math.floor(Math.random() * 5000) + 3000)
      visitorData.push(Math.floor(Math.random() * 2000) + 1000)
    }
  } else if (trendTimeUnit.value === 'week') {
    // 周数据，最近12周
    for (let i = 11; i >= 0; i--) {
      xAxisData.push(`第${12-i}周`)
      visitData.push(Math.floor(Math.random() * 30000) + 20000)
      visitorData.push(Math.floor(Math.random() * 12000) + 8000)
    }
  } else if (trendTimeUnit.value === 'month') {
    // 月数据，最近12个月
    const monthNames = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    const currentMonth = new Date().getMonth()
    
    for (let i = 11; i >= 0; i--) {
      const monthIndex = (currentMonth - i + 12) % 12
      xAxisData.push(monthNames[monthIndex])
      visitData.push(Math.floor(Math.random() * 120000) + 80000)
      visitorData.push(Math.floor(Math.random() * 50000) + 30000)
    }
  }
  
  // 设置图表选项
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['访问量', '访客数'],
      right: 10,
      top: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '访问量',
        type: 'line',
        smooth: true,
        data: visitData,
        itemStyle: {
          color: '#409EFF'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0, color: 'rgba(64, 158, 255, 0.3)'
            }, {
              offset: 1, color: 'rgba(64, 158, 255, 0.1)'
            }]
          }
        }
      },
      {
        name: '访客数',
        type: 'line',
        smooth: true,
        data: visitorData,
        itemStyle: {
          color: '#67C23A'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0, color: 'rgba(103, 194, 58, 0.3)'
            }, {
              offset: 1, color: 'rgba(103, 194, 58, 0.1)'
            }]
          }
        }
      }
    ]
  }
  
  // 设置图表
  visitTrendChartInstance.setOption(option)
  
  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    visitTrendChartInstance && visitTrendChartInstance.resize()
  })
}

// 渲染内容分析图
const renderContentAnalysisChart = () => {
  if (!contentAnalysisChart.value) return
  
  // 销毁旧实例
  if (contentAnalysisChartInstance) {
    contentAnalysisChartInstance.dispose()
  }
  
  // 创建新实例
  contentAnalysisChartInstance = echarts.init(contentAnalysisChart.value, null, {
    renderer: 'canvas'
  })
  
  // 模拟数据
  let data = []
  
  if (contentAnalysisTab.value === 'category') {
    // 分类分布
    data = [
      { value: 1548, name: '国内' },
      { value: 1246, name: '国际' },
      { value: 986, name: '财经' },
      { value: 854, name: '科技' },
      { value: 745, name: '体育' },
      { value: 682, name: '娱乐' },
      { value: 521, name: '教育' },
      { value: 432, name: '健康' }
    ]
  } else if (contentAnalysisTab.value === 'region') {
    // 区域分布
    data = [
      { value: 2356, name: '北京' },
      { value: 1823, name: '上海' },
      { value: 1245, name: '广州' },
      { value: 987, name: '深圳' },
      { value: 745, name: '杭州' },
      { value: 652, name: '南京' },
      { value: 543, name: '武汉' },
      { value: 432, name: '成都' },
      { value: 321, name: '其他' }
    ]
  } else if (contentAnalysisTab.value === 'source') {
    // 信源分布
    data = [
      { value: 1245, name: '新华网' },
      { value: 986, name: '人民网' },
      { value: 854, name: '央视网' },
      { value: 745, name: '中国日报' },
      { value: 682, name: '环球时报' },
      { value: 521, name: '财经网' },
      { value: 432, name: '科技日报' },
      { value: 321, name: '其他' }
    ]
  }
  
  // 设置图表选项
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: data.map(item => item.name)
    },
    series: [
      {
        name: contentAnalysisTab.value === 'category' ? '分类分布' : 
              contentAnalysisTab.value === 'region' ? '区域分布' : '信源分布',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['40%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '14',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: data
      }
    ]
  }
  
  // 设置图表
  contentAnalysisChartInstance.setOption(option)
  
  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    contentAnalysisChartInstance && contentAnalysisChartInstance.resize()
  })
}

// 渲染用户分析图
const renderUserAnalysisChart = () => {
  if (!userAnalysisChart.value) return
  
  // 销毁旧实例
  if (userAnalysisChartInstance) {
    userAnalysisChartInstance.dispose()
  }
  
  // 创建新实例
  userAnalysisChartInstance = echarts.init(userAnalysisChart.value, null, {
    renderer: 'canvas'
  })
  
  let option = {}
  
  if (userAnalysisTab.value === 'device') {
    // 访问设备
    option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center',
        data: ['移动端', '桌面端', '平板', '其他']
      },
      series: [
        {
          name: '访问设备',
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['40%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '14',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: [
            { value: 65, name: '移动端' },
            { value: 30, name: '桌面端' },
            { value: 4, name: '平板' },
            { value: 1, name: '其他' }
          ]
        }
      ]
    }
  } else if (userAnalysisTab.value === 'source') {
    // 访问来源
    option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['访问量', '访客数'],
        right: 10,
        top: 0
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'value'
      },
      yAxis: {
        type: 'category',
        data: ['直接访问', '搜索引擎', '外部链接', '社交媒体', '邮件营销', '其他']
      },
      series: [
        {
          name: '访问量',
          type: 'bar',
          stack: 'total',
          label: {
            show: true,
            position: 'insideRight'
          },
          emphasis: {
            focus: 'series'
          },
          data: [18500, 12800, 8500, 6200, 2100, 1500],
          itemStyle: {
            color: '#409EFF'
          }
        },
        {
          name: '访客数',
          type: 'bar',
          stack: 'total',
          label: {
            show: true,
            position: 'insideRight'
          },
          emphasis: {
            focus: 'series'
          },
          data: [9200, 7500, 4800, 3600, 1200, 800],
          itemStyle: {
            color: '#67C23A'
          }
        }
      ]
    }
  } else if (userAnalysisTab.value === 'region') {
    // 地域分布
    option = {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center',
        data: ['华东', '华北', '华南', '西南', '东北', '西北', '华中']
      },
      series: [
        {
          name: '地域分布',
          type: 'pie',
          radius: '70%',
          center: ['40%', '50%'],
          data: [
            { value: 28, name: '华东' },
            { value: 22, name: '华北' },
            { value: 18, name: '华南' },
            { value: 12, name: '西南' },
            { value: 8, name: '东北' },
            { value: 7, name: '西北' },
            { value: 5, name: '华中' }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
  }
  
  // 设置图表
  userAnalysisChartInstance.setOption(option)
  
  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    userAnalysisChartInstance && userAnalysisChartInstance.resize()
  })
}

// 初始化
onMounted(() => {
  // 初始化图表
  nextTick(() => {
    renderVisitTrendChart()
    renderContentAnalysisChart()
    renderUserAnalysisChart()
  })
})
</script>

<style scoped>
/* 统计卡片样式 */
.stat-card {
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.05);
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

/* 标签页样式 */
:deep(.content-tabs .el-tabs__header),
:deep(.user-tabs .el-tabs__header) {
  margin: 0;
  padding: 0;
}

:deep(.content-tabs .el-tabs__nav-wrap),
:deep(.user-tabs .el-tabs__nav-wrap) {
  padding: 0;
}

:deep(.content-tabs .el-tabs__item),
:deep(.user-tabs .el-tabs__item) {
  height: 32px;
  line-height: 32px;
  padding: 0 10px;
}

/* 排名样式 */
.rank-1 {
  background-color: #f56c6c;
  color: white;
}

.rank-2 {
  background-color: #e6a23c;
  color: white;
}

.rank-3 {
  background-color: #f0c78a;
  color: white;
}

/* 表格样式优化 */
:deep(.el-table) {
  --el-table-header-bg-color: var(--el-fill-color-light) !important;
  --el-table-row-hover-bg-color: rgba(0, 0, 0, 0.02) !important;
  border-radius: 8px;
  overflow: hidden;
}


:deep(.el-card__header) {
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

</style>